<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    :title="getTitle"
    width="1200"
    :showFooter="showFooter"
    destroyOnClose
  >

    <!--引用表格-->
    <BasicTable @register="registerTable" :loading="confirmLoading" @expand="handleExpand">
      <!-- 内嵌table区域 begin -->
      <template #expandedRowRender="{record}">
        <CaishuiMiddleUserSubTable :relTenantIds="expandedRowKeys[0]"/>
      </template>
      <!-- 内嵌table区域 end -->
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button v-if="showCreate" type="primary" preIcon="ant-design:plus-outlined" @click="handleCreate"> 新增中台默认管理员</a-button>
        <a-button type="primary" preIcon="ant-design:plus-outlined" @click="handleBinding"> 绑定关联用户</a-button>
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)"/>
      </template>
      <!--角色插槽-->
      <template #middleOptAuthSlot="{record}">
        <a-tag v-if="record.middleOptAuth==0" color="blue" >系统默认管理员</a-tag>
        <a-tag v-if="record.middleOptAuth==1" color="green" >管理员</a-tag>
        <a-tag v-if="record.middleOptAuth==2" color="red" >渠道角色</a-tag>
      </template>
      <!--状态插槽-->
      <template #statusSlot="{record}">
        <a-badge v-if="record.status===1" color="green" :text="record.status_dictText" />
        <a-badge v-if="record.status===2" color="red" :text="record.status_dictText" />
      </template>
    </BasicTable>
    <!--用户抽屉-->
    <UserDrawer @register="registerEditDrawer" @success="handleSuccess" />
    <!--用户选择-->
    <UserSelectModal rowKey="id" :params="selectUserParams" @register="registerSelUserModal" @getSelectResult="handleSelectSuccess" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
import { ref, useAttrs } from "vue";
import { BasicDrawer, useDrawer, useDrawerInner } from "/@/components/Drawer";
import { BasicTable, TableAction } from "/@/components/Table";
import { useListPage } from "/@/hooks/system/useListPage";
import { caishuiMiddleUserColumns } from "../CaishuiServiceCompany.data";
import { bindingUser, removeOne, userList } from "../CaishuiServiceCompany.api";
import { useMessage } from "/@/hooks/web/useMessage";
import UserDrawer from "/@/views/manage/middleUser/UserDrawer.vue";
import { useModal } from "/@/components/Modal";
import UserSelectModal from "/@/components/Form/src/jeecg/components/modal/UserSelectModal.vue";
import CaishuiMiddleUserSubTable from "../subTables/CaishuiMiddleUserSubTable.vue";

// 展开key
const expandedRowKeys = ref<any[]>([]);
// 声明Emits
const emit = defineEmits(['success', 'register']);
const attrs = useAttrs();
const showFooter = ref(false);
//获取标题
const getTitle = ref("服务公司关联用户列表");
const queryParam = ref<any>({});
const recordData = ref<any>({});
const confirmLoading = ref<boolean>(false);
const { createMessage, createConfirm } = useMessage();
const showCreate = ref(false);
const selectUserParams = ref<any>({
  userType: 2,
  middleOptAuth: 0,
  notUserIds: '',
});

  //抽屉赋值
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ confirmLoading: false, showFooter: showFooter.value });
    recordData.value = data.record;
  });
  // 注册用户选择 modal
  const [registerSelUserModal, selUserModal] = useModal();
  //注册table数据
  const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
    tableProps: {
      title: '',
      api: userList,
      columns: caishuiMiddleUserColumns,
      canResize:false,
      useSearchForm: false,
      striped: true,
      showIndexColumn: true,
      showActionColumn: true,
      actionColumn: {
        width: 80,
        fixed: 'right',
      },
      beforeFetch: (params) => {
        params.tenantId = recordData.value.tenantId ? recordData.value.tenantId : '0';
        return Object.assign(params, queryParam.value);
      },
      afterFetch: (data) => {
        if(data.length > 0){
          showCreate.value = false;
          let userIds = [];
          data.forEach((item) => {
            userIds.push(item.userId);
          });
          selectUserParams.value.notUserIds = userIds.join(",");
        }else {
          showCreate.value = true;
        }
      }
    },
  });
  const [registerTable, { reload, collapseAll, updateTableDataRecord, findTableDataRecord, getDataSource }, { rowSelection, selectedRowKeys }] = tableContext;
  //注册drawer
  const [registerEditDrawer, { openDrawer }] = useDrawer();

/**
 * 展开事件
 * */
function handleExpand(expanded, record){
  expandedRowKeys.value=[];
  if (expanded === true) {
    expandedRowKeys.value.push(record.relTenantIds);
  }
}

/**
 * 新增事件
 */
function handleCreate() {
  openDrawer(true, {
    isUpdate: false,
    showFooter: true,
    record: {companyIds: recordData.value.id,relTenantIds: recordData.value.tenantId,middleOptAuth: 0},
  });
}

/**
 * 绑定用户
 */
function handleBinding() {
  selUserModal.openModal();
}

/**
 * 选择用户成功后事件
 * @param data
 */
async function handleSelectSuccess(data){
  if(data){
    let model = {
      tenantId: recordData.value.tenantId,
      userList: data,
    };
    confirmLoading.value = true;
    await bindingUser(model)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          reload();
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }
}

/**
 * 成功回调
 */
function handleSuccess() {
  reload();
}

/**
 * 操作栏
 */
function getTableAction(record) {
  return [
    {
      label: '移除',
      icon: 'ant-design:delete-outlined',
      ifShow: record.isDefault == 0,
      popConfirm: {
        title: '是否确认移除？',
        confirm: handleRemove.bind(null, record),
      }
    }
  ];
}

/**
 * 移除
 * @param record
 */
async function handleRemove(record){
  await removeOne({ id: record.id }, handleSuccess);
}

</script>
<style lang="less" scoped>
.jeecg-basic-table-form-container {
  margin-bottom: -10px;
  .table-page-search-submitButtons {
    display: block;
    white-space: nowrap;
  }
  .query-group-cust{
    width: calc(50% - 15px);
    min-width: 100px !important;
  }
  .query-group-split-cust{
    width: 30px;
    display: inline-block;
    text-align: center
  }
}
</style>
